<template>
  <el-dialog title="分配角色" :visible.sync="showRoleDialog" @close="cancel">
    <!-- 多选框组 -->
    <el-checkbox-group v-model="checkList">
      <el-checkbox v-for="item in list" :key="item.id" :label="item.id">{{
        item.name
      }}</el-checkbox>
    </el-checkbox-group>
    <!-- 定义fonter插槽名称 -->
    <el-row slot="footer" type="flex" justify="center">
      <el-col :span="6">
        <el-button size="small" type="primary" @click="btnOk">确定</el-button>
        <el-button size="small" @click="cancel">取消</el-button>
      </el-col>
    </el-row>
  </el-dialog>
</template>
<script>
import { getRoleList } from "@/api/setting";
import { getUserDetailById } from "@/api/user";
import { assignRoles } from "@/api/employees";
export default {
  props: {
    showRoleDialog: {
      type: Boolean,
      default: false,
    },
    userId: {
      //需要知道当前处理的是那个用户
      type: String,
      default: null,
      require: true, //要求必须写
    },
  },
  data() {
    return {
      list: [], //负责存储所有角色的id
      checkList: [], //这个数组负责存储当前用户所拥有(勾选上的选项)的id
    };
  },
  created() {
    //获取所有的角色
    this.getRoleList();
  },
  methods: {
    async getRoleList() {
      const { rows } = await getRoleList({ page: 1, pageSize: 20 });
      this.list = rows;
    },
    //这个方法需要在点击弹窗的时候父组件调用，但是因为props传值是个异步的，所以this.userId这样是取不到值
    //父组件里通过ref调用子组件方法
    async getUserDetailById(id) {
      const { roleIds } = await getUserDetailById(id);
      this.checkList = roleIds;
    },
    cancel() {
      this.checkList = []; //清空原来的数组
      this.$emit("update:showRoleDialog", false);
    },
    async btnOk() {
      await assignRoles({ id: this.userId, roleIds: this.checkList });
      this.$emit("update:showRoleDialog", false);
      // this.$parent.showRoleDialog=false //这样也可以关闭弹层
    },
  },
};
</script>